package com.mundus.world.renderbuffer;

import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.newdawn.slick.util.Log;

public class FrameBuffer {
	private int _fbId;
	private IntBuffer _drawBuffer;
	List<RenderTarget> _renderTargets;

	public int getFrameBufferId(){ return _fbId;}
	public List<RenderTarget> getRenderTargets(){ return _renderTargets;}
	
	public FrameBuffer(RenderTarget... renderTargets){
		_renderTargets = new ArrayList<RenderTarget>();	
		for(RenderTarget rt : renderTargets)
			_renderTargets.add(rt);
	}
	
	public FrameBuffer(){
		_renderTargets = new ArrayList<RenderTarget>();	
	}
	
	public void addRenderTarget(RenderTarget renderTarget){
		_renderTargets.add(renderTarget);
	}
	
	public void generateFrameBuffer() throws LWJGLException{					
		int colorRTCount = 0;
		_fbId = GL30.glGenFramebuffers();			
		GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, _fbId);
	
		for(int i = 0; i < _renderTargets.size(); i++){
			_renderTargets.get(i).initRenderTarget();
			
			if(_renderTargets.get(i).getAttachment() != GL30.GL_DEPTH_ATTACHMENT)
				colorRTCount++;
		}
		
		_drawBuffer = BufferUtils.createIntBuffer(colorRTCount);
		for(int c = 0; c < colorRTCount; c++)
			_drawBuffer.put(c, _renderTargets.get(c).getAttachment());
			
		GL20.glDrawBuffers(_drawBuffer);
		
		if(GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) != GL30.GL_FRAMEBUFFER_COMPLETE)
			Log.error("Frame buffer not complete");
		
		GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
	}
	
	
	public void bindForWriting(){
		GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, _fbId);
		GL20.glDrawBuffers(_drawBuffer);
	}
	
	public void bindForReading(){
		GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, _fbId);
		GL20.glDrawBuffers(_drawBuffer);
	}
	
	public void unbindBuffer(){
		GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
	}
}
